<template>
  <div class="page-common-layout custom-tablePage-container">
    <div class="screen-conditions-container">
      <ScreenConditions :isDataType="false">
        <template slot="conditions">
          <a-input
            v-model="condition.code"
            placeholder="请输入编号"
            style="width:300px"
          ></a-input>
          <a-select
            class="project-select"
            showSearch
            allowClear
            placeholder="请选择专业"
            :filter-option="filterOption"
            v-model="condition.major"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in majorSource"
              :key="item.uuid"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
          <a-select
            class="project-select"
            showSearch
            allowClear
            placeholder="请选择类别"
            :filter-option="filterOption"
            v-model="condition.category"
          >
            <a-select-option
              :value="item.dicItemCode"
              v-for="item in categorySource"
              :key="item.uuid"
            >
              {{ item.dicItemName }}
            </a-select-option>
          </a-select>
          <a-input
            v-model="condition.name"
            placeholder="请选择设备/材料名称"
            style="width:300px"
          ></a-input>
          <a-input
            v-model="condition.remark"
            placeholder="请输入描述"
            style="width:300px"
          ></a-input>

          <a-input
            style="width:300px"
            v-model="condition.creator"
            placeholder="请输入提交人"
          ></a-input>
          <a-range-picker
            :placeholder="['封样开始时间', '封样结束时间']"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-model="condition.date"
            :show-time="false"
          />
          <a-range-picker
            :placeholder="['提交开始日期', '提交结束日期']"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
            v-model="condition.createTime"
            :show-time="false"
          />
        </template>
        <template slot="operate">
          <a-button class="cu-btn-primary" icon="search" @click="search()">
            查询
          </a-button>
          <a-button class="cu-btn-filter" icon="reload" @click="reset()">
            重置
          </a-button>
        </template>
      </ScreenConditions>
    </div>
    <div class="table-body-container">
      <div class="table-operate">
        <a-button
          @click="handleAddModal({}, 1)"
          class="cu-btn-primary margin-bottom-xs"
          icon="plus"
          v-action="'fygl_table_add'"
        >
          新增
        </a-button>
        <!-- 批量导入 -->
        <a-button
          @click="handleBatchModal()"
          class="cu-btn-primary margin-bottom-xs"
          icon="import"
        >
          批量导入
        </a-button>
      </div>
      <div class="table-main">
        <vxe-table
          ref="xTable"
          height="99%"
          align="left"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
          :row-config="{ keyField: 'uuid' }"
          :expand-config="{
            reserve: true,
            visibleMethod: visibleMethod,
          }"
        >
          <vxe-column type="expand" width="26">
            <template #content="{ row }">
              <div class="expand-wrapper">
                <vxe-table
                  align="center"
                  border="inner"
                  :data="row.historys || []"
                  :column-config="{ resizable: true }"
                  show-overflow
                  show-header-overflow
                  size="small"
                >
                  <vxe-column field="versionNumber" title="版本号">
                  </vxe-column>
                  <vxe-column field="categoryDesc" title="类别"> </vxe-column>
                  <vxe-column field="code" title="编号"> </vxe-column>
                  <vxe-column field="name" title="设备/材料名称"> </vxe-column>
                  <vxe-column field="scheduledTime" title="封样时间">
                  </vxe-column>
                  <vxe-column field="remark" title="描述"> </vxe-column>
                  <vxe-column title="设计封样">
                    <template #default="{ row }">
                      <div class="files-icon">
                        <!-- 预览 -->
                        <a-tooltip placement="top">
                          <template slot="title">
                            预览
                          </template>
                          <a-icon
                            type="eye"
                            @click="previewFile(row, '设计封样')"
                          />
                        </a-tooltip>
                        <!-- 下载 -->
                        <a-tooltip placement="top" v-action:fygl_table_download>
                          <template slot="title">
                            下载
                          </template>
                          <a-icon
                            type="download"
                            @click="
                              downloadFile(row.designSampleSealing, '设计封样')
                            "
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                  <vxe-column title="施工封样">
                    <template #default="{ row }">
                      <div class="files-icon">
                        <!-- 预览 -->
                        <a-tooltip placement="top">
                          <template slot="title">
                            预览
                          </template>
                          <a-icon
                            type="eye"
                            @click="previewFile(row, '施工封样')"
                          />
                        </a-tooltip>
                        <!-- 下载 -->
                        <a-tooltip placement="top" v-action:fygl_table_download>
                          <template slot="title">
                            下载
                          </template>
                          <a-icon
                            type="download"
                            @click="
                              downloadFile(
                                row.constructionSealingSample,
                                '施工封样'
                              )
                            "
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                  <vxe-column field="reason" title="驳回原因"> </vxe-column>
                  <vxe-column
                    field="operate"
                    width="80"
                    title="操作"
                    fixed="right"
                  >
                    <template #default="{ row }">
                      <div class="text-button-group">
                        <a-tooltip placement="top">
                          <template slot="title">
                            封样对比
                          </template>
                          <icon-fonts
                            icon="icon-duibi"
                            class="contrast"
                            @change="handleContrastImageModal(row)"
                          ></icon-fonts>
                        </a-tooltip>
                        <a-tooltip placement="top">
                          <template slot="title">
                            查看
                          </template>
                          <a-icon
                            type="file-search"
                            @click="handleAddModal(row, 3)"
                          />
                        </a-tooltip>
                      </div>
                    </template>
                  </vxe-column>
                </vxe-table>
              </div>
            </template>
          </vxe-column>
          <vxe-column
            type="seq"
            width="50"
            title="序号"
            align="center"
          ></vxe-column>
          <vxe-column field="code" title="编号"> </vxe-column>
          <vxe-column field="majorDesc" title="专业"> </vxe-column>
          <vxe-column field="categoryDesc" title="类别"> </vxe-column>
          <vxe-column field="name" title="设备/材料名称"> </vxe-column>
          <vxe-column field="scheduledTime" title="封样时间"> </vxe-column>
          <vxe-column field="remark" title="描述"> </vxe-column>
          <vxe-column title="设计封样">
            <template #default="{ row }">
              <div class="files-icon">
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon type="eye" @click="previewFile(row, '设计封样')" />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top" v-action:fygl_table_download>
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    @click="downloadFile(row.designSampleSealing, '设计封样')"
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="施工封样">
            <template #default="{ row }">
              <div class="files-icon">
                <input
                  accept="image/*"
                  @change="uploadImage($event)"
                  type="file"
                  ref="upload"
                  id="upload"
                  style="display: none"
                />
                <a-tooltip placement="top">
                  <template slot="title">
                    上传
                  </template>
                  <a-icon
                    type="cloud-upload"
                    @click="handleUpload(row)"
                    :class="[!row.sgfyUpload && 'disabled']"
                  />
                </a-tooltip>
                <!-- 预览 -->
                <a-tooltip placement="top">
                  <template slot="title">
                    预览
                  </template>
                  <a-icon type="eye" @click="previewFile(row, '施工封样')" />
                </a-tooltip>
                <!-- 下载 -->
                <a-tooltip placement="top" v-action:fygl_table_download>
                  <template slot="title">
                    下载
                  </template>
                  <a-icon
                    type="download"
                    @click="
                      downloadFile(row.constructionSealingSample, '施工封样')
                    "
                  />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="状态" width="140">
            <template #default="{ row }">
              <div class="state" :class="[filterStateClass(row.approveStatus)]">
                {{ filterStateName(row.approveStatus) }}
              </div>
            </template>
          </vxe-column>
          <vxe-column
            field="operate"
            width="180"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-tooltip placement="top">
                  <template slot="title">
                    查看
                  </template>
                  <a-icon type="file-search" @click="handleAddModal(row, 3)" />
                </a-tooltip>

                <a-tooltip placement="top">
                  <template slot="title">
                    封样对比
                  </template>
                  <icon-fonts
                    icon="icon-duibi"
                    class="contrast"
                    @change="handleContrastImageModal(row)"
                  ></icon-fonts>
                </a-tooltip>

                <a-tooltip placement="top" v-if="row.approveRecord">
                  <template slot="title">
                    审批记录
                  </template>
                  <icon-fonts
                    icon="icon-shenpi"
                    class="record"
                    @change="gotoApprovalRecord(row)"
                  ></icon-fonts>
                </a-tooltip>

                <a-tooltip
                  placement="top"
                  v-action="'fygl_table_submit'"
                  v-if="row.submit"
                >
                  <template slot="title">
                    提交
                  </template>
                  <icon-fonts
                    icon="icon-fabu-tijiao-tijiaobanben"
                    class="submit"
                    @change="handleSubmit(row)"
                  ></icon-fonts>
                </a-tooltip>

                <a-tooltip placement="top" v-if="row.approve">
                  <template slot="title">
                    审批
                  </template>
                  <icon-fonts
                    icon="icon-shenpi1"
                    class="approve"
                    @change="handleAddModal(row, 4)"
                  ></icon-fonts>
                </a-tooltip>

                <a-tooltip v-action="'fygl_table_edit'" v-if="row.edit">
                  <template slot="title">
                    编辑
                  </template>
                  <a-icon type="edit" @click="handleAddModal(row, 2)" />
                </a-tooltip>

                <a-tooltip v-action="'fygl_table_del'" v-if="row.del">
                  <template slot="title">
                    删除
                  </template>
                  <a-icon type="delete" @click="handleDelClick(row)" />
                </a-tooltip>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="table-pager">
        <vxe-pager
          size="small"
          background
          :current-page.sync="pager.page"
          :page-size.sync="pager.pageSize"
          :total="pager.total"
          :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes']"
          :page-sizes="[20, 50, 100, 500]"
          @page-change="paginationChange"
        >
          <template #left>
            <div class="vxe-pager-left-tip-container">
              共<span>{{ pager.total }}</span
              >条
            </div>
          </template>
        </vxe-pager>
      </div>
    </div>
    <!-- 审批记录 -->
    <comment-modal ref="commentModal"></comment-modal>
    <!-- 新增/编辑/查看 -->
    <addModal
      :visible.sync="addModal.visible"
      :parameter="addModal.row"
      :pageOperate="addModal.operate"
    ></addModal>
    <!-- 封样对比 -->
    <contrastImageModal
      :visible.sync="contrastImageModal.visible"
      :parameter="contrastImageModal.row"
    ></contrastImageModal>
    <!-- 预览 -->
    <viewImageModal
      :visible.sync="viewImageModal.visible"
      :parameter="viewImageModal.row"
      :subtitle="viewImageModal.name"
    ></viewImageModal>
    <!-- 上传图片 -->
    <uploadImgModal
      :visible.sync="uploadImgModal.visible"
      :row="uploadImgModal.row"
    ></uploadImgModal>
    <!-- 批量导入 -->
    <batchModal :visible.sync="batchModal.visible"></batchModal>
  </div>
</template>

<script>
// 封样管理
import { axios } from "@/utils/request";
import { _getUUID } from "@/utils/util.js";
import { downLoadBatchFileByArraybuffer } from "@/utils/TopVUI";
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import addModal from "./components/addModal.vue";
import contrastImageModal from "./components/contrastImageModal.vue";
import batchModal from "./components/batchModal.vue";
import viewImageModal from "./components/viewImageModal.vue";
import uploadImgModal from "./components/uploadImgModal.vue";

//审批记录
import commentModal from "@/pages/workflow/oaLeave/comment.vue";
import { getDicItemByCode } from "@/api/common";
import {
  pageSealSampleManage,
  deleteSealSampleManage,
  zipDesignBriefing,
  submitSealSampleManage,
  updateConstructionSealingSample,
} from "@/api/design";

export default {
  components: {
    ScreenConditions,
    commentModal,
    addModal,
    contrastImageModal,
    viewImageModal,
    uploadImgModal,
    batchModal,
  },
  data() {
    return {
      //专业
      majorSource: [],
      //类别
      categorySource: [],
      //查询条件
      condition: {
        // 编号
        code: "",
        //专业
        major: undefined,
        // 类别
        category: undefined,
        // 设备/材料名称
        name: "",
        // 封样时间
        date: [],
        // 描述
        remark: "",
        //提交时间
        createTime: [],
        //提交人
        creator: "",
      },
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      // 新增/编辑/查看
      addModal: {
        visible: false,
        row: {},
        operate: 1,
      },
      //对比图片
      contrastImageModal: {
        visible: false,
        row: {},
      },
      //预览
      viewImageModal: {
        visible: false,
        row: {},
        name: "",
      },
      currentRow: {},
      //上传图片
      uploadImgModal: {
        visible: false,
        row: {},
      },
      //批量导入
      batchModal: {
        visible: false,
      },
    };
  },
  mounted() {
    Promise.all([this.getData(), this.getTableData()]);
  },
  methods: {
    //批量导入
    handleBatchModal() {
      this.batchModal.visible = true;
    },

    async getData() {
      //专业
      this.majorSource = await this.getDicCodeData("major");
      //节点类型
      this.categorySource = await this.getDicCodeData("category");
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //文件大小转换
    sizeTostr(size = 0) {
      size = Number(size);
      var data = "";
      if (size < 0.1 * 1024) {
        //如果小于0.1KB转化成B
        data = size.toFixed(2) + "B";
      } else if (size < 0.1 * 1024 * 1024) {
        //如果小于0.1MB转化成KB
        data = (size / 1024).toFixed(2) + "KB";
      } else if (size < 0.1 * 1024 * 1024 * 1024) {
        //如果小于0.1GB转化成MB
        data = (size / (1024 * 1024)).toFixed(2) + "MB";
      } else {
        //其他转化成GB
        data = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";
      }
      var sizestr = data + "";
      var len = sizestr.indexOf("\.");
      var dec = sizestr.substr(len + 1, 2);
      if (dec == "00") {
        //当小数点后为00时 去掉小数部分
        return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
      }
      return sizestr;
    },

    //导入模板
    handleUpload(row) {
      if (!row.sgfyUpload) {
        return;
      }
      this.uploadImgModal.row = row;
      this.uploadImgModal.visible = true;
      //   return;
      //   this.currentRow = row;
      //   if (!row.sgfyUpload) {
      //     return;
      //   }
      //   this.$refs.upload.click();
    },
    // uploadImage(event) {
    //   return new Promise((resolve, reject) => {
    //     // 获取文件对象
    //     let file = event.target.files[0];
    //     // 获取文件名
    //     let fileName = file.name;
    //     // 获取文件大小，单位为字节
    //     let fileSize = this.sizeTostr(file.size);
    //     // 获取文件类型
    //     let lastIdx = fileName.lastIndexOf(".");
    //     let fileType = "." + fileName.substring(lastIdx + 1);
    //     //
    //     let formData = new FormData();
    //     formData.append("bucket", "yx-cloud-vue");
    //     formData.append("file", file);
    //     axios
    //       .post(`/document/minio/uploadfile`, formData, {
    //         headers: {
    //           "Content-Type": "multipart/form-data",
    //         },
    //       })
    //       .then((res) => {
    //         let source = {
    //           dfsFileUuid: res.dfsFileUuid,
    //           url: res.url,
    //           fileName,
    //           fileSize,
    //           fileType,
    //         };
    //         this.updateFormImage(source);
    //         resolve();
    //       })
    //       .catch((_) => {
    //         reject();
    //       })
    //       .finally((_) => {
    //         event.target.value = "";
    //       });
    //   });
    // },
    // updateFormImage(file) {
    //   let { uuid, constructionSealingSample } = this.currentRow;
    //   let fileList = JSON.parse(constructionSealingSample ?? "[]") || [];
    //   fileList.push(file);
    //   let formJson = {
    //     uuid,
    //     constructionSealingSample: JSON.stringify(fileList),
    //   };
    //   updateConstructionSealingSample(formJson)
    //     .then((res) => {
    //       if (res.statusCode === 200 || res === 1) {
    //         this.$message.success("上传成功", 1.5);
    //         this.getTableData();
    //       } else {
    //         this.$message.error(res?.message ?? "上传失败");
    //       }
    //     })
    //     .catch((_) => {
    //       this.$message.error(_?.message ?? "上传失败");
    //     })
    //     .finally((_) => {});
    // },

    //封样对比
    handleContrastImageModal(row) {
      this.contrastImageModal.row = row;
      this.contrastImageModal.visible = true;
    },

    // 新增/编辑/查看
    handleAddModal(row, operate) {
      this.addModal.operate = operate;
      this.addModal.row = row;
      this.addModal.visible = true;
    },

    //预览
    previewFile(row, name) {
      this.viewImageModal.name = name;
      this.viewImageModal.row = row;
      this.viewImageModal.visible = true;
    },

    //审批记录
    gotoApprovalRecord(record) {
      this.$refs.commentModal.getCommentList(record.uuid);
    },

    //下载
    downloadFile(files, name) {
      let fileList = JSON.parse(files ?? "[]");
      let ids = fileList.map((v) => v.dfsFileUuid);
      zipDesignBriefing({ fileIds: ids.toString() })
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, name);
        })
        .catch((_) => {});
    },

    //删除
    handleDelClick(row) {
      let dataLength = this.tableData.length;
      let that = this;
      that.$confirm({
        title: "提示",
        content: "确定删除该数据吗？删除之后不可恢复！",
        okText: "确定",
        cancelText: "取消",
        icon: () =>
          that.$createElement("a-icon", {
            props: {
              key: "warning",
              type: "exclamation-circle",
              twoToneColor: "#faad14",
            },
          }),
        onOk() {
          deleteSealSampleManage({ uuid: row.uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("删除成功", 1.5);
                if (dataLength == 1 && that.pager.page > 1) {
                  that.pager.page -= 1;
                }
                that.getTableData();
              } else {
                that.$message.error(res.message);
              }
            })
            .catch((_) => {});
        },
      });
    },

    //提交
    handleSubmit(row) {
      let that = this;
      let { uuid } = row;
      const h = this.$createElement;
      this.$confirm({
        title: "您确定提交所选内容?",
        content: "",
        okText: "确定",
        okType: "primary",
        cancelText: "取消",
        centered: true,
        icon: () =>
          h("a-icon", {
            props: {
              type: "question-circle",
              theme: "filled",
            },
            style: "color:#FAAD14",
          }),
        onOk() {
          that.loading = true;
          submitSealSampleManage({ uuid })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                that.$message.success("提交成功", 1.5);
                that.getTableData();
              } else {
                that.$message.error(res?.message ?? "提交失败");
              }
            })
            .catch((_) => {
              that.$message.error(res?.message ?? "提交失败");
            })
            .finally(() => {
              that.loading = false;
            });
        },
        onCancel() {},
      });
    },

    //查询
    search() {
      this.pager.page = 1;
      this.getTableData();
    },

    //重置
    reset() {
      this.condition = {
        // 编号
        code: "",
        //专业
        major: undefined,
        // 类别
        category: undefined,
        // 设备/材料名称
        name: "",
        // 封样时间
        date: [],
        // 描述
        remark: "",
        //提交时间
        createTime: [],
        //提交人
        creator: "",
      };
      this.search();
    },

    visibleMethod({ row }) {
      if (row.historys && row.historys.length != 0) {
        return true;
      } else {
        return false;
      }
    },

    //查询列表数据
    getTableData() {
      this.loading = true;
      let { page, pageSize } = this.pager;
      let {
        code,
        category = "",
        date,
        createTime,
        creator,
        name,
        remark,
        major = "",
      } = this.condition;
      return new Promise((resolve, reject) => {
        pageSealSampleManage({
          page,
          pageSize,
          code,
          major,
          category,
          startTime: date?.[0] ?? "",
          endTime: date?.[1] ?? "",
          startTimeSub: createTime?.[0] ?? "",
          endTimeSub: createTime?.[1] ?? "",
          creator,
          name,
          remark,
        })
          .then((res) => {
            this.tableData = res.data?.rows || [];
            this.pager.total = res.data?.totalCount || 0;
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.pager.total = 0;
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },

    //监听分页切换
    paginationChange({ currentPage, pageSize }) {
      this.pager.page = currentPage;
      this.pager.pageSize = pageSize;
      this.getTableData();
    },

    filterStateName(val) {
      switch (val) {
        case 0:
          return "待提交";
        case 1:
          return "审批中";
        case 2:
          return "审批通过";
        case 3:
          return "驳回";
        case 4:
          return "上传施工封样";
        default:
          return "-";
      }
    },

    filterStateClass(val) {
      switch (val) {
        case 0:
          return "default";
        case 1:
          return "ing";
        case 2:
          return "lock";
        case 3:
          return "error";
        case 4:
          return "upload";
        default:
          return "";
      }
    },

    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>

<style lang="scss" scoped>
.screen-conditions-container {
  flex-shrink: 0;
  .more {
    cursor: pointer;
    font-size: 14px;
    color: #1890ff;
    margin-left: 10px;
    padding-top: 6px;
    .anticon {
      font-size: 12px;
    }
  }
}
.expand-wrapper {
  padding: 10px;
  box-sizing: border-box;
}
.state {
  &::before {
    position: relative;
    display: inline-block;
    content: "";
    width: 8px;
    height: 8px;
    border-radius: 0px 0px 0px 0px;
    border-radius: 50%;
    margin-right: 10px;
  }
  &.default {
    &::before {
      background: #8c8c8c;
    }
  }
  &.ing {
    &::before {
      background: #f07f17;
    }
  }
  &.lock {
    &::before {
      background: #239b53;
    }
  }
  &.upload {
    &::before {
      background: #0098ff;
    }
  }

  &.error {
    &::before {
      background: #ff3f4a;
    }
  }
}
</style>
